package com.wolfalpha.lwtool.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.wolfalpha.lwtool.R;
import com.wolfalpha.lwtool.constant.Application;
import com.wolfalpha.lwtool.map.MapsAndLists;
import com.wolfalpha.lwtool.vo.Job;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Handler;
import android.preference.PreferenceManager;

/**
 * 动态抓取 只能停留在界面抓取，退出界面则停止
 * 
 * @author ttStudio
 * 
 */
public class DynamicZQActivity extends Activity implements OnClickListener {

	private Button btn_start;
	private Button btn_stop;
	private TextView tv_progress;
	private boolean zq = false;//是否开始抓取

	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				updateProgress(String.valueOf(msg.obj));
				break;
			case 1:
				zqnum++;
				refreshList();
				tv_num.setText(String.valueOf(zqnum));
				tv_num.invalidate();
				break;
			case 2:
				if(adapter!=null)
					 adapter.notifyDataSetChanged();
				 break;
			case 3:
				zq = false;
				Application.getBaseService(DynamicZQActivity.this).stopWork(true);
				btn_start.setClickable(true);
				updateProgress(String.valueOf(msg.obj));
				break;
			}
			super.handleMessage(msg);
		}
	};

	private ScrollView svPro;
	private ListView listResource;
	private List<Job> dbs;
	private TextView tv_frequency;
	private int fre;
	private TextView tv_num;
	private int zqnum = 0;
	private SimpleAdapter adapter = null;
	private ArrayList<Map<String, ?>> list = null;

	public void updateProgress(String str) {
		StringBuffer sb = new StringBuffer(tv_progress.getText().toString());
		tv_progress.setText(sb.append(str + "\n").toString());
		tv_progress.invalidate();
		scrollToBottom(svPro, tv_progress);
	}
	@Override
	protected void onResume(){
		// 设置当前活动状态
		Application.setFrontActivity(Application.N_DYNAMIC);
		Log.d("当前活动：", Application.N_DYNAMIC);
		super.onResume();
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_zq);
		initView();
		setListeners();

		// 注册广播
		registerBoradcastReceiver();

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(mBroadcastReceiver); 
	}
	private void setListeners() {
		btn_start.setOnClickListener(this);
		btn_stop.setOnClickListener(this);
	}

	public void refreshList(){
		if(list!=null){
			list.clear();
		}
		else{
			list = new ArrayList<Map<String, ?>>();
		}
		dbs = MapsAndLists.getJobs();
		System.out.println("DY size:"+dbs.size());
		
        for (int i = 0; i < dbs.size(); i++) {
            Map<String, Integer> m = new HashMap<String, Integer>();
            m.put("jsid", dbs.get(i).getId());
            list.add(m);
        }
        handler.sendEmptyMessage(2);
	}
	// 初始化界面控件
	private void initView() {
		btn_start = (Button) findViewById(R.id.startzq);
		btn_stop = (Button) findViewById(R.id.stopzq);
		btn_stop.setClickable(false);
		tv_progress = (TextView) findViewById(R.id.zqprogress);
		tv_num = (TextView) findViewById(R.id.zqnum);
		tv_frequency = (TextView) findViewById(R.id.zqfrequency);
		svPro = (ScrollView) findViewById(R.id.sv_zqprogress);
		listResource = (ListView) findViewById(R.id.zqobjects);

        String[] from = { "jsid" };
        int[] to = { R.id.jsid };
        refreshList();
        adapter = new SimpleAdapter(this, list, R.layout.jz_simple_item, from, to);
        listResource.setAdapter(adapter);
        
		SharedPreferences shp = PreferenceManager
				.getDefaultSharedPreferences(this);
		fre = shp.getInt("frequency", 0);
		tv_frequency.setText(this.getResources().getStringArray(
				R.array.frequency)[fre]);
	}

	@Override
	public void onClick(View view) {
		if (view.getId() == R.id.startzq) {
			if(!zq){
				zq = true;
				Application.getBaseService(DynamicZQActivity.this).dynamicZQ();
				btn_start.setClickable(false);
			}
		}
		if (view.getId() == R.id.stopzq) {
//			Application.getBaseService(DynamicZQActivity.this).stopWork(true);
//			Message msg = new Message();
//			msg.what = 3;
//			msg.obj = "已取消";
//			handler.sendMessage(msg);
		}
	}

	/**
	 * 注册广播
	 */
	private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(Application.N_DYNAMIC)) {
				Message msg = new Message();
					msg.what = 0;
					msg.obj = intent.getStringExtra("msg");
					if (String.valueOf(msg.obj).equals("GET")) {
						msg.what = 1;
					}if(String.valueOf(msg.obj).contains("FINISH")){
						msg.what = 3;
					}
					handler.sendMessage(msg);
					
			}
		}

	};

	public void registerBoradcastReceiver() {
		IntentFilter myIntentFilter = new IntentFilter();
		myIntentFilter.addAction(Application.N_DYNAMIC);
		// 注册广播
		registerReceiver(mBroadcastReceiver, myIntentFilter);
	}

	/**
	 * ' 始终显示最下面
	 * 
	 * @param scroll
	 * @param inner
	 */
	public static void scrollToBottom(final View scroll, final View inner) {
		Handler mHandler = new Handler();
		mHandler.post(new Runnable() {
			public void run() {
				if (scroll == null || inner == null) {
					return;
				}
				int offset = inner.getMeasuredHeight() - scroll.getHeight();
				if (offset < 0) {
					offset = 0;
				}
				scroll.scrollTo(0, offset);
			}
		});
	}

}
